﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Text.Json.Serialization
{
    /// <summary>
    /// 表示可为空的<see langword="DateTime?"/>类型的json转换器
    /// </summary>
    public class DateTimeNullableConverter : JsonConverter<DateTime?>
    {
        private readonly string _format;

        /// <inheritdoc cref="DateTimeNullableConverter"/>
        /// <param name="format">日期格式</param>
        public DateTimeNullableConverter(string format)
        {
            _format = format;
        }
        
        /// <inheritdoc/>
        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
            {
                return null;
            }

            return DateTime.Parse(reader.GetString());
        }

        /// <inheritdoc/>
        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteNullValue();
            }
            else
            {
                writer.WriteStringValue(value.Value.ToString(_format));
            }
        }
    }
}
